<template>
  <el-card class="chat-container" :body-style="{ padding: '0' }">
    <div class="chat-messages" ref="messagesContainer">
      <el-scrollbar>
        <div class="messages-wrapper">
          <div v-for="(message, index) in messages" :key="index">
            <!-- 用户消息 -->
            <el-card
              v-if="message.role === 'user'"
              class="message user"
              shadow="hover"
            >
              <div slot="header" class="message-header">
                <el-avatar icon="el-icon-user"></el-avatar>
                <span>你</span>
              </div>
              <div class="message-content">
                {{ message.content }}
              </div>
            </el-card>

            <!-- AI 回复 -->
            <el-card
              v-else
              class="message assistant"
              shadow="hover"
            >
              <div slot="header" class="message-header">
                <el-avatar icon="el-icon-s-custom"></el-avatar>
                <span>AI 助手</span>
              </div>
              <div class="message-content">
                <el-collapse v-model="activeNames[index]" v-if="message.reasoning">
                  <el-collapse-item title="思考过程" name="reasoning">
                    <div class="reasoning-content">
                      {{ message.reasoning }}
                    </div>
                  </el-collapse-item>
                </el-collapse>
                <div class="answer-content" v-if="message.answer">
                  <div class="answer-header">
                    <el-tag size="small" type="success">回答</el-tag>
                  </div>
                  {{ message.answer }}
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <div class="chat-input">
      <el-input
        v-model="userInput"
        type="textarea"
        :rows="5"
        :maxlength="1000"
        show-word-limit
        placeholder="请输入您的问题..."
        @keyup.enter.native="handleSend"
      ></el-input>
      <el-button type="primary" @click="handleSend" :loading="loading" :icon="loading ? 'el-icon-loading' : 'el-icon-s-promotion'">
        {{ loading ? '发送中...' : '发送' }}
      </el-button>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'DeepSeekChat',
  data() {
    return {
      messages: [],
      userInput: '',
      loading: false,
      activeNames: {}
    };
  },

  methods: {
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messagesContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    },

    async handleSend() {
      if (!this.userInput.trim()) {
        this.$message.warning('请输入内容');
        return;
      }

      // 添加用户消息
      this.messages.push({
        role: 'user',
        content: this.userInput
      });

      this.scrollToBottom();
      this.loading = true;

      try {
        // 创建新的助手消息
        const assistantMessage = {
          role: 'assistant',
          reasoning: '',
          answer: ''
        };
        this.messages.push(assistantMessage);

        // 创建 EventSource 连接
        const response = await fetch('/lingxi/deepseek/chat', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            messages: [{
              role: 'user',
              content: this.userInput
            }]
          })
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
          const { done, value } = await reader.read();
          if (done) break;

          // 解码数据
          const chunk = decoder.decode(value);
          const lines = chunk.split('\n');

          // 处理每一行数据
          for (const line of lines) {
            if (line.startsWith('data: ')) {
              try {
                const data = JSON.parse(line.slice(6));
                if (data.type === 'reasoning') {
                  assistantMessage.reasoning += data.content;
                } else if (data.type === 'answer') {
                  assistantMessage.answer += data.content;
                }
                this.scrollToBottom();
              } catch (e) {
                console.error('Parse error:', e);
              }
            }
          }
        }

      } catch (error) {
        console.error('Chat error:', error);
        this.$message.error(error.response?.data?.error || '网络错误');
      } finally {
        this.loading = false;
        this.userInput = '';
      }
    }
  },

  mounted() {
    this.scrollToBottom();
  }
};
</script>

<style scoped>
.chat-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--el-bg-color);
}

.chat-messages {
  flex: 1;
  overflow: hidden;
  padding: 20px;
  background: var(--el-bg-color);
}

.messages-wrapper {
  padding: 10px;
}

.message {
  margin-bottom: 20px;
  max-width: 85%;
}

.message.user {
  margin-left: auto;
}

.message.assistant {
  margin-right: auto;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 10px;
}

.message-content {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.6;
}

.reasoning-content {
  padding: 10px;
  background: var(--el-bg-color-page);
  border-radius: 4px;
  margin: 10px 0;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

.answer-content {
  padding: 10px;
  margin-top: 10px;
}

.answer-header {
  margin-bottom: 10px;
}

.chat-input {
  padding: 20px;
  border-top: 1px solid var(--el-border-color-lighter);
  background: var(--el-bg-color);
  display: flex;
  gap: 10px;
}

.chat-input .el-input {
  flex: 1;
}

/* 自定义折叠面板样式 */
:deep(.el-collapse) {
  border: none;
}

:deep(.el-collapse-item__header) {
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

:deep(.el-collapse-item__content) {
  padding: 0;
}

/* 滚动条样式 */
:deep(.el-scrollbar__wrap) {
  overflow-x: hidden;
}
</style>
